<template>
  <div class="cart container">
    <!-- 这是购物车 -->
    <header>
      <i
        class='iconfont icon-fanhui'
        @click="goHome"
      ></i>
      <span class="spann">购物车</span>
      <span
        @click='isNavBar'
        v-text='isNavStatus ? "完成":"编辑"'
      ></span>
      <!-- 通过选择不同的字体 v-text -->
    </header>
    <section v-if='list.length'>
      <div class='cart-title'>
        <!-- {{isCheckedAll}} -->
        <van-checkbox
          @click='checkAllFn'
          :value="isCheckedAll"
        ></van-checkbox>
        <span>商品</span>
        <!--         <span v-if((isCheckedAll)>1)>{{isCheckedAll}}</span>
        <span v-else(0)></span> -->
      </div>
      <ul>
        <li
          v-for="(item,index) in list"
          :key="index"
        >
          <!--           {{item}}       前期测试-->
          <div class='check'>
            <!--             <van-checkbox v-model="item.checked"></van-checkbox> -->
            <van-checkbox
              @click='checkItem(index)'
              v-model="item.checked"
            ></van-checkbox>
          </div>
          <h2>
            <img
              :src="item.goods_imgUrl"
              alt="暂时不能显示照片"
            >
          </h2>
          <div class='goods'>
            <div class='goods-title'>
              <!-- <span>{{item.goods_name}} </span> -->
              <span
                style="textOverflow: ellipsis;whiteSpace: nowrap"
                :title="item.goods_name"
              >{{item.goods_name}}</span>
              <i
                class='iconfont icon-lajitong'
                @click="delGoodsFn(item.id)"
              ></i><!-- 垃圾桶  单删除-->
              <!--<svg
                class="icon"
                aria-hidden="true"
              >
                <use xlink:href="#icon-lajitong"></use>
              </svg> -->
            </div>
            <div class='goods-price'>¥{{item.goods_price}}</div>
            <van-stepper
              @change="changeNum($event,item)"
              v-model="item.goods_num"
              integer
              min="1"
              max="10"
            />
          </div>
          <!-- $event 这个代表什么？？？ -->
          <!-- 这个@change是vants vant-stepper 的事件 -->
        </li>
      </ul>
    </section>
    <section v-else>
      没有购物车数据
      <router-link to='/home'>去首页逛逛吧</router-link>
    </section>
    <footer v-if='list.length'>
      <div class='radio'>
        <!--         <van-checkbox v-model="checked"></van-checkbox> -->
        <van-checkbox
          @click='checkAllFn'
          :value="isCheckedAll"
        ></van-checkbox>
      </div>
      <div
        class='total'
        v-show="!isNavStatus"
      >
        <div>
          共有
          <span class='total-active'>&nbsp;{{total.num}}</span>
          &nbsp;件商品
        </div>
        <div>
          <span>总计：</span>
          <span class='total-active'>¥{{total.price.toFixed(2)}}&nbsp;元&nbsp;/&nbsp;RMB&nbsp;</span>
        </div>
      </div>
      <div
        class='order'
        v-if='isNavStatus'
        @click='delGoodsFn'
      >删除</div>
      <div
        class='order'
        v-else
        @click="goOrder"
      >去结算</div>
      <!-- 下面的要分成两块，因为还要加事件！！ -->
      <!-- <div class='order'>{{isNavStatus?"删除":"去结算"}}</div> -->
    </footer>
    <section v-else>
    </section><!-- 忘了拿来干什么了 -->
    <Tabbar></Tabbar>
  </div>

</template>
<script src="./iconfont.js"></script>
<script>
import Tabbar from "../components/common/Tabbar.vue";
import http from "@/common/api/request.js";
import { Toast } from "mint-ui";
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
  name: "Cart" /*对应的是router.js里面的 name: "Cart",*/,
  data() {
    return {
      isNavStatus: false, //编辑|完成
      checked: true, //应该把他去除
      //list: [], // 数据名称存储 不能这样定义 否者 会把下面list覆盖
      //list2: [],
    };
  },
  computed: {
    ...mapState({
      list: (state) => state.cart.list,
      selectList: (state) => state.cart.selectList, //cart.js；里面
    }),
    ...mapGetters(["isCheckedAll", "total"]),
    goodsList() {
      return this.selectList.map((id) => {
        return this.list.find((v) => v.id == id);
      });
    },
  },
  created() {
    this.getData();
  },
  methods: {
    goHome() {
      this.$router.push("home");
    },
    ...mapMutations(["cartList", "checkItem", "initOrder"]),
    ...mapActions(["checkAllFn", "delGoodsFn"]),
    async getData() {
      //购物车 进入购物车就要查询用户有哪些购物数据，用来加载
      let res = await http.$axios({
        url: "/api/selectCart",
        method: "post",
        headers: {
          //请求头
          token: true,
        },
      });
      /*         .then((res) => {
          //console.log(res); 正常显示
          this.cartList(res.data);
          if (res.success) {
            //Toast("更新数据中");
          } else {
            //Toast("加载失败,请重新登录");
          }
        }); */
      //console.log(res); undefind
      //console.log(res.data);
      //if (res.data) {
      res.data.forEach((v) => {
        v["checked"] = true;
      }); //给每个元素一个checked属性 true  在前端加，不必存在后端

      this.cartList(res.data);
      //}
    },
    //点击编辑|完成
    isNavBar() {
      this.isNavStatus = !this.isNavStatus; //点击取反
    },
    //修改数量
    changeNum(value, item) {
      //当前购物车商品id以及修改后的数量 传递给后端
      //console.log(value, item.id); //item/detial是什么？？？//value是vants里面的数值 个数
      // item 是 商品的id值
      http.$axios({
        method: "post",
        url: "/api/updateNum",
        headers: {
          //请求头
          token: true, //这里是true
        },
        data: {
          id: item.id,
          num: value,
        },
      });
      //.then((res) => {
      //  console.log(res);
      //}); //这里要注释掉否则前端就会空等//一直转圈
    },
    //去结算
    goOrder() {
      //this.$router.push("/order");
      if (!this.selectList.length) {
        Toast("请至少选择一件商品");
        return;
      }
      Toast("跳转中,请稍后");

      let newList = [];
      this.list.forEach((item) => {
        this.selectList.filter((v) => {
          // v 是匿名函数  //这里的做法是遍历item，一旦有item.id的数据就存在newList里面  个人理解
          //了解这里的filter做法  新建一个newList存储 selectList.filter数据 selectList 存储的是商品的所有数据
          if (v == item.id) {
            newList.push(item);
          }
        });
      });
      //生成一个订单
      http
        .$axios({
          url: "/api/addOrder",
          method: "post",

          headers: {
            //请求头
            token: true, //这里是true 传过去token
          },
          data: {
            arr: newList,
          },
        })
        .then((res) => {
          //console.log(res);
          //console.log(res);  res是返回一个订单号的，前端要存储
          if (!res.success) {
            //这里有疑问，后端只会返回success:true和不返回把？？
            Toast("网络在开小差,出错了......");
            return;
          }
          //存储订单号 到vuex里面
          this.initOrder(res.data);
          //进入提交订单页面
          //页面跳转
          this.$router.push({
            /*             path: "/order",
            query: {
              detail: JSON.stringify(this.selectList),
            }, */
            //显示传递
            //name: "/order",//这里式不对的，参照index.js
            /* name: "Order",//这个可以 */
            //隐式传递
            /*             parms: {
              detail: JSON.stringify(this.selectList),
            }, */
            //显式传递
            path: "/order",
            query: {
              detail: JSON.stringify(this.selectList),
              goodsList: JSON.stringify(this.goodsList),
              //路径传值一定要解析，否则可能会出现问题
            },
          });
        });

      /*//由于这里没有注释，导致页面跳转了两次，导致各种奇怪的错误
        //页面跳转
      this.$router.push({
        path: "/order",
        //显示传递
        query: {
          detail: JSON.stringify(this.selectList),
        },
      }); */
    },
  },
  components: {
    Tabbar,
  },
};
</script>

<style scoped lang='scss'>
/* .icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
} */
.container {
  height: 88vh;
}
.cart header {
  color: white;
  display: flex;
  justify-content: space-between; //
  align-items: center; //左中右布局
  height: 1.4667rem;
  background-color: #b0352f;
  font-size: 0.533rem;
  span {
    padding: 0px 0.5333rem;
  }
  .spann {
    padding-left: 1.5333rem;
    letter-spacing: 0.533rem; //购物车行距
    font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS",
      sans-serif;
  }
  i {
    padding: 0.533rem;
    font-size: 0.666rem; //调整图标大小
  }
}
section {
  background-color: #f5f5f5;
  .cart-title {
    display: flex;
    padding: 0.2rem 0.533333rem;
    span {
      padding: 0 1em;
      font-weight: 500;
      font-size: 0.48rem;
    }
    span :first-child {
      padding: 0 1.4rem;
    }
  }
  ul {
    border: none;
    list-style: none;
    display: flex;
    flex-direction: column;
    list-style-type: none;
    li {
      width: 90vw;
      border: #c0bcbc solid 1px; //要写完整才起作用
      border-left: #c0bcbc solid 2px;
      border-right: #c0bcbc solid 2px;
      list-style: none;
      display: flex;
      //justify-content: baseline;
      justify-content: space-around;
      align-items: center;
      padding: 0.16rem 0.533333rem;
      margin: 0.213333rem 0;
      background-color: #fff;
      .check {
        padding-right: 0.373333rem;
      }
      .goods {
        display: flex;
        flex-direction: column;
        padding-left: 0.4rem;
        //position: fixed;
        width: 50vw;
        right: 10px;
        font-size: 0.32rem;
        .goods-title {
          display: flex;
          i {
            //display: inline-block;
            font-size: 0.586666rem;
            padding-left: 0.2667rem;
            position: relative;
            right: -70%;
          }
          span {
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
            //display: inline-block;
            width: 100%;
            font-size: 0.4rem;
            display: inline-block;
            //text-align: center;
            //span标签中实现换行
            word-break: normal;
            width: auto;
            display: block;
            white-space: pre-wrap;
            word-wrap: break-word;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
        .goods-price {
          padding: 0.08rem 0;
          color: #b0352f;
          position: relative;
          font-size: 25px;
          right: -72%;
        }
        //这里是 .van-stepper  穿透
        ::v-deep .van-stepper {
          text-align: right;
        }
      }
      img {
        width: 1.973333rem;
        height: 1.973333rem;
      }
    }
  }
}
footer {
  //left:0rem;
  //bottom:0rem;
  //position:fixed;
  padding-left: 0.26667rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 1.28rem;
  border-top: 0.053333rem solid #ccc;
  .radio {
    padding: 0 0.4rem;
  }
  .total {
    flex: 1;
    font-size: 0.32rem;
    .total-active {
      color: #b0352f;
      /* 如letter-spacing:20px;即设置了字与字之间的距离间隔为15px。 */
      //letter-spacing: 0.5333rem;
      //word-spacing: 10px;
    }
  }
  .order {
    width: 2.5rem;
    line-height: 1.28rem;
    color: #fff;
    text-align: center;
    font-size: 0.426666rem;
    background-color: #b0352f;
  }
}
</style>
